package com.paas.demo.controller;

import com.plat.paas.utils.ImageUtil;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;

/**
 * @author : pengjie
 * @version v1.0.0
 * @ClassName : VideoController
 * @Description : TODO
 * @email : 627799251@qq.com
 * @Date : 2019/5/28 12:20
 */
public class VideoController{


        /**
         * 获取指定视频的帧并保存为图片至指定目录
         * @param videofile  源视频文件路径
         * @param framefile  截取帧的图片存放路径
         * @throws Exception
         */
        public static void fetchFrame(String videofile, String framefile) throws Exception {

            File targetFile = new File(framefile);

            FFmpegFrameGrabber ff = new FFmpegFrameGrabber(videofile);
            ff.start();
            int lenght = ff.getLengthInFrames();
            int i = 0;
            Frame frame  = null;
            while (i < lenght) {
                // 过滤前5帧，避免出现全黑的图片，依自己情况而定
                frame  = ff.grabFrame();
                if ((i > 10) && (frame .image != null)) {
                    break;
                }
                i++;
            }
            //创建BufferedImage对象
            Java2DFrameConverter converter = new Java2DFrameConverter();
            BufferedImage bufferedImage = converter.getBufferedImage(frame);

            ImageIO.write(bufferedImage, "jpg", targetFile);
            //ff.flush();
            ff.stop();

        }


        public static void main(String[] args) {
            try {
                VideoController.fetchFrame("C:\\workspace\\data\\PLAN1558944918613.mp4", "C:\\workspace\\data\\test6.jpg");
                ImageUtil.thumb("C:\\workspace\\data\\test6.jpg", 100, 100, "C:\\workspace\\data\\test6_100x100.jpg");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

}
